<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import ImportMember from '@/components/ImportMember/index.vue'
import { getMemberList,getMemberLevelList,getChannelList,getMemberLayeringList,getMemberTagPage } from '@/api/Member/index.js';
import { StoreManagementList } from '@/api/BussinessMenage/index'
import { exportFile } from '@/utils/common.js';
import { useMemberQuery } from './Hooks/index';
import EditLabelsDialog from './Components/EditLabelsDialog.vue'

const seachTable = ref(null);
const importMemberRef = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();

// 处理跳转查询
const { memberQuery,memberQueryKeysReflection} = useMemberQuery();
const memberQueryLength = computed(()=>{
  return Object.values(memberQuery.value).filter(item=>item).length;
})
const handlerMemberQuery = async ()=>{
  for(let key in memberQuery.value){
    if(memberQuery.value[key] !== ''){
      // 消费值,默认值是数组的赋值为数组
      if(Array.isArray(formInline.value[memberQueryKeysReflection[key]].model)){
        formInline.value[memberQueryKeysReflection[key]].model = memberQuery.value[key];
      }else{
        formInline.value[memberQueryKeysReflection[key]].model = memberQuery.value[key];
      }
      
    }
  }
  if(memberQueryLength.value){
    // 把值清除 避免重复查询
    for(let key in memberQuery.value){
      memberQuery.value[key] = ''
    }
    await seachTable.value.handlerSearch()
  }
}
const isReq = ref(false)
// 新增编辑回退时候刷新列表
onActivated(async ()=>{
  await Promise.any([
     _getChannelList(),
     _getMemberTagPage(),
     _getMemberLayeringList(),
     _getMemberLevelList(),
     _getStoreManagementList(),
  ])
  await handlerMemberQuery()
})
const formInline = ref([

    {
      type: "input",
      prop: "userName",
      placeholder: "会员姓名",
      label: "",
      model: "",
      width:180
    },
    {
      type: "input",
      prop: "phone",
      placeholder: "手机号码",
      label: "",
      model: "",
      width:180
    },
    // {
    //     type: "select",
    //     placeholder: "会员等级",
    //     label: '',
    //     filterable: true,
    //     prop: 'levelId',
    //     data:[],
    //     model: "",
    //     width:180
    // },
    {
        type: "cascader",
        state:'default',
        placeholder: "会员标签",
        label: '',
        filterable: true,
        collapseTags:true,
        collapseTagsTooltip:true,
        props:{
          multiple:true,
          checkStrictly:false,
          emitPath:true
        },
        prop: 'tagIds',
        data:[],
        model: [],
        style: {
            width: '290px'
        }
    },
    {
        type: "select",
        placeholder: "会员分层",
        label: '',
        filterable: true,
        prop: 'layerId',
        data:[],
        model: "",
        width:180
    },
    {
        type: "select",
        placeholder: "来源渠道",
        label: '',
        filterable: true,
        prop: 'sourceChannelId',
        data:[],
        model: "",
        width:180
    },
    // {
    //     type: "select",
    //     placeholder: "注册门店",
    //     label: '',
    //     prop: 'storeId',
    //     filterable: true,
    //     data:[],
    //     model: "",
    //     width:260
    // },
])
const _getMemberLevelList = async ()=>{
  let result = await getMemberLevelList();
  formInline.value[2].data = result.map(lis=>{
    return {
      label:lis.levelName,
      value:lis.id
    }
  });
}
const _getMemberLayeringList = async ()=>{
  let result = await getMemberLayeringList();
  formInline.value[4].data = result.map(lis=>{
    return {
      label:lis.layeringName,
      value:lis.id
    }
  });
}
const tagLabel = ref([]);
const _getMemberTagPage = async ()=>{
  let result = await getMemberTagPage({
    page:{
      current:1,
      size:9999
    }
  });
  result.records.forEach(item => {
    tagLabel.value = [...tagLabel.value, item.labelName,...(item?.secondLabelList?.map(cItem => cItem.labelName) ?? [])]
  })
  formInline.value[3].data = result.records.map(lis=>{
    return {
      label:lis.labelName,
      value:lis.id,
      children:lis.secondLabelList.map(lis=>{
        return {
          label:lis.labelName,
          value:lis.id
        }
      })
    }
  });
}
const _getChannelList = async ()=>{
  let result = await getChannelList();
  formInline.value[5].data = result.map(lis=>{
    return {
      label:lis.sourceChannel,
      value:lis.id
    }
  });
}
// 获取门店列表
const _getStoreManagementList = async ()=>{
  let result = await StoreManagementList({page:{size: 10000, current: 1}});
  formInline.value[6].data = result.records.map(lis=>{
    return {
      label:lis.storeName,
      value:lis.id
    }
  });
}

const btnLefts = ref([
    {
        label:"导入",
        plain:false,
        type:"success",
        show:true,
        plain:true,
        img:new URL("@/assets/icon/btn-import.png",import.meta.url),
        click:async ()=>{
            importMemberRef.value.importFlag = true;
        }
    },
    {
        label:"导出",
        plain:false,
        type:"primary",
        show:true,
        plain:true,
        img:new URL("@/assets/icon/btn-export.png",import.meta.url),
        style:"border-color:#0C268C;color:#0C268C",
        click:async ()=>{

          const loading = ElLoading.service({
                lock: true,
                text: '导出中',
                background: 'rgba(255, 255, 255, 0.7)',
            })
            try{

              await exportFile(`/jy-member/mgmt/user/export`,'post',`会员信息`,{},searchData.value)
              loading.close()
            }catch(e){
              loading.close()
            }
        }
    },

])
const btnRights = ref([

])

const isShowEditTagDialog = ref(false)
const itemRow = ref({})
// 编辑标签弹窗
const editTag = async (item)=>{
  itemRow.value = item;
  isShowEditTagDialog.value = true;
}
const tableConfig = ref([
    {
      prop: "userName",
      label: "会员姓名",
      width:200
    },
    {
      prop: "phone",
      label: "手机号",
      width:200
    },
    // {
    //   prop: "levelName",
    //   label: "会员等级",
    //   width:200
    // },

    {
      prop: "sex",
      label: "性别",
      width:100,
      format:(value)=>{
        return ["女","男"][value];
      }
    },
    {
      prop: "birthday",
      label: "生日",
      width:200
    },
    // {
    //   prop: "integral",
    //   label: "可用积分",
    //   width:100
    // },
    {
      prop: "principal",
      label: "负责人",
      width:100
    },
    {
      prop: "transactor",
      label: "办理人",
      width:200
    },
    {
      prop: "tags",
      label: "标签",
      width:200,
      format:(value)=>{
        if(value && value.length>0){
          return value.join('、')
        }else{
          return '-';
        }

      }
    },
    {
      prop: "layer",
      label: "分层",
      width:200
    },
    {
      prop: "sourceChannelName",
      label: "来源渠道",
      width:100
    },
    {
      prop: "lastTimeInStore",
      label: "上次到店日期",
      width:200
    },
    // {
    //   prop: "storeName",
    //   label: "注册门店",
    //   width:200
    // },
    {
      prop: "registerTime",
      label: "注册时间",
      width:200
    },
    {
      type: "action",
      label: "操作",
      width: 200,
      btns: [
        {
          label: () => "编辑标签",
          type:"success",
          click: async (row) => {
            editTag(row)
          },
        },
        {
          label: () => "详情",
          type:"primary",
          click: async (row) => {
            router.push({name:'MemberChildManagementDetail',query:{id:row.id}})
          },
        },

      ],
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);

const searchData = ref({})
const handlerSearch = async (formInline)=>{
    if(memberQueryLength.value) return
    formInline.tagIds = formInline.tagIds ? formInline.tagIds.split(',') : []
    searchData.value = formInline;
    tableLoading.value = true;
    console.log('formInline', formInline)
    try{
        let res = await getMemberList(formInline);
        totalPage.value = Number(res.total);
        tableData.value = res.records;
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const refresh = () => {
    seachTable.value.initSearch()
}
const refresh1 = () => {
    seachTable.value.handlerSearch()
}

</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
        >
        </SeachTable>
        <ImportMember ref="importMemberRef" @success="refresh"></ImportMember>
        <EditLabelsDialog v-model:show="isShowEditTagDialog" :item="itemRow" @refresh="refresh1"></EditLabelsDialog>
    </div>
</template>
